Public Class clDataTableACSV
    Public Shared Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String)
        DataTable2CSV(table, filename, vbTab)
    End Sub

    Public Shared Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String, ByVal sepChar As String, Optional ByVal writeHeader As Boolean = True)
        Dim writer As System.IO.StreamWriter
        Try
            writer = New System.IO.StreamWriter(filename)

            ' first write a line with the columns name
            Dim sep As String = ""
            Dim builder As New System.Text.StringBuilder

            If writeHeader = True Then
                For Each col As DataColumn In table.Columns
                    builder.Append(sep).Append(col.ColumnName)
                    sep = sepChar
                Next
                writer.WriteLine(builder.ToString())
            End If

            ' then write all the rows
            For Each row As DataRow In table.Rows
                sep = ""
                builder = New System.Text.StringBuilder

                For Each col As DataColumn In table.Columns
                    Dim val As String = CStr(row(col.ColumnName))
                    If val.Contains(",") Then val = Chr(34) & val & Chr(34)
                    val = val.Replace(vbCrLf, "")
                    builder.Append(sep).Append(val)
                    sep = sepChar
                Next
                writer.WriteLine(builder.ToString())
            Next
        Finally
            If Not writer Is Nothing Then writer.Close()
        End Try
    End Sub
End Class
